// pages/category/category.js
let app = getApp();
import {
        list
} from '../../../api/product'

import {
        productCategoryList
} from '../../../api/productCategory'

const util = require('../../../utils/util.js')

Page({

        /**
         * 页面的初始数据
         */
        data: {
                statusBarHeight: 22,
                pageNum: 1,
                pageSize: 20,
                searchBottom:"", //搜索栏底部的位置
                secondBottom: "", //二级导航底部的位置
                firstTop: "", //二级导航的顶部位置
                firstHeight:"", //一级导航的高度
                thirdTop:"",//三级分类的顶部位置
                adSrc: "http://cdn.rzico.com/v4.0/test1.png",
                firstLevelInfo: [],
                showSecondLevel: [],
                isShowSecond:true,
                secondLevelInfo: [],
                thirdLevelInfo: [],
                checkNext:false,//用来检查上拉加载是不是要切换到下一个类目
                scrollTop:"", //记录当前滚动的距离
                eInfo:"" //暂存购物车动画的e数据
        },

        /**
         * 生命周期函数--监听页面加载
         */
        onLoad: function(options) {
                console.info("options--" + JSON.stringify(options))
                
                this.getCategoryList(() => {
                        this.firstLevelFun(options.id)
                })

        },

        detailsClick(e) {
                // console.info("e--" + JSON.stringify(e.currentTarget.dataset.id))
                let id = e.currentTarget.dataset.id
                wx.navigateTo({
                        url: '/pages/goods/product/details?id='+id,
                })
        },
        /**
         * 生命周期函数--监听页面初次渲染完成
         */
        onReady: function() {
                
        },

        /**
         * 生命周期函数--监听页面显示
         */
        onShow: function() {
                let statusBarHeight = app.globalData.statusBarHeight
                this.getFirstTop()
                this.setData({
                        statusBarHeight: statusBarHeight
                })
        },

        //跳转搜索页
        categorySearch(){
                wx.navigateTo({
                        url: '/pages/goods/search/index',
                })
        },

        //获取顶部的高度
        // firstTop: "", //二级导航的顶部位置
        // thirdTop: "",//三级分类的顶部位置
        getFirstTop(){
                //选择id
                var _this = this;
                let query = wx.createSelectorQuery()
                query.select('.category-search').boundingClientRect()
                query.select('.addCart').boundingClientRect()
                query.select('.category-firstLevel').boundingClientRect()
                query.exec((res) => {
                        console.info("节点的res--" + JSON.stringify(res))
                        _this.setData({
                                firstTop: res[0].bottom,
                                firstHeight: res[1].top - res[0].bottom - 10
                        })
                        console.info("节点的firstHeight--" + this.data.firstHeight)
                })
        },

        //获取分类列表的信息
        getCategoryList(callback) {
                let _this = this
                // console.info("一级分类的数据app.globalData.mchId-*-" + JSON.stringify(app.globalData.mchId))
                productCategoryList({
                        mchId: app.globalData.mchId
                }).then(
                        res => {
                                console.log("商品分类列表res--" + JSON.stringify(res))
                                if (res.type == 'success') {
                                        _this.formateDateFromFirstAndSecond(res.data)
                                        if (callback) {
                                                callback()
                                        }
                                }
                        }
                ).catch(error => {
                        console.log(error)
                })
        },

        //获取商品列表信息
        getProductrequest(id, callback) {
                let _this = this
                console.log("商品信息pageNum--" + JSON.stringify(_this.data.pageNum))
                list({
                        pageNum: _this.data.pageNum,
                        pageSize: _this.data.pageSize,
                        mchId: app.globalData.mchId,
                        productCategoryId: id,
                        sortField: "product_category_id"
                }).then(
                        res => {
                                console.log("商品信息res--" + JSON.stringify(res))
                                if (res.type == 'success') {
                                        if (callback) {
                                                callback(res.data.data)
                                        }
                                        // _this.data.productList = res.data.data
                                        // _this.setData({
                                        //         productList: _this.data.productList
                                        // })
                                }
                        }
                ).catch(error => {
                        console.log(error)
                })

        },

        //整理一级和二级分类数据
        formateDateFromFirstAndSecond(data) {
                if (data.length > 0) {
                        let firstLevelInfo = []
                        let secondLevelInfo = []
                        // //console.info("一二级分类的数据data-*-" + JSON.stringify(data))
                        data.map((item) => {
                                let firstLevelInfoItem = {}
                                firstLevelInfoItem.id = item.id
                                firstLevelInfoItem.name = item.name
                                firstLevelInfoItem.thumbnail = item.thumbnail
                                firstLevelInfoItem.isShow = item.isShow
                                firstLevelInfoItem.isSelsected = false
                                firstLevelInfo.push(firstLevelInfoItem)
                                if (item.childrens.length > 0) {
                                        item.childrens.map((item1) => {
                                                let secondLevelInfoItem = {}
                                                secondLevelInfoItem.parentId = item.id
                                                secondLevelInfoItem.id = item1.id
                                                secondLevelInfoItem.name = item1.name
                                                secondLevelInfoItem.thumbnail = util.thumbnail(item1.thumbnail, 75, 75)
                                                secondLevelInfoItem.isShow = item1.isShow
                                                secondLevelInfoItem.isSelsected = false
                                                secondLevelInfo.push(secondLevelInfoItem)
                                        })
                                }
                        })
                        //console.info("一级分类的数据firstLevelInfo-*-" + JSON.stringify(firstLevelInfo))
                        console.info("二级分类的数据secondLevelInfo-*-" + JSON.stringify(secondLevelInfo))
                        this.setData({
                                firstLevelInfo: firstLevelInfo,
                                secondLevelInfo: secondLevelInfo
                        })
                }
        },

        //整理商品列表数据
        formateDateFromProductList(data, type) {
                //console.info("type--" + type)
                //console.info("开始整理商品数据data--" + JSON.stringify(data))
                let thirdLevelInfoNew = []
                let thirdLevelIdList = []
                if (data.length > 0) {
                        data.map((item) => {
                                thirdLevelIdList.push(item.productCategoryId)
                        })
                        thirdLevelIdList = Array.from(new Set(thirdLevelIdList)); //父级id去重
                        if (thirdLevelIdList.length > 0) {
                                thirdLevelIdList.map((item) => {
                                        let thirdLevelInfoItem = {}
                                        thirdLevelInfoItem.productCategoryId = item
                                        thirdLevelInfoItem.productList = []
                                        data.map((item1) => {
                                                if (item == item1.productCategoryId) {
                                                        thirdLevelInfoItem.productCategoryName = item1.productCategoryName
                                                        let productListItem = {}
                                                        productListItem.id = item1.id
                                                        productListItem.marketPrice = item1.marketPrice
                                                        productListItem.name = item1.name
                                                        productListItem.price = item1.price
                                                        productListItem.goodsId = item1.goodsId
                                                        productListItem.thumbnail = util.thumbnail(item1.thumbnail, 200, 200)
                                                        productListItem.stock = item1.stock
                                                        productListItem.sku = item1.sku
                                                        productListItem.maxLimit = item1.maxLimit
                                                        productListItem.promotions = item1.promotions
                                                        productListItem.coupons = item1.coupons
                                                        thirdLevelInfoItem.productList.push(productListItem)
                                                }
                                        })
                                        thirdLevelInfoNew.push(thirdLevelInfoItem)
                                })
                                // //console.info("thirdLevelInfoNew--" + JSON.stringify(thirdLevelInfoNew))
                        }
                        let thirdLevelInfo = []
                        if (type == "push"){
                                thirdLevelInfo = this.data.thirdLevelInfo 
                                if (thirdLevelInfo.length > 0 && thirdLevelInfoNew.length > 0){
                                        let thirdLevelInfoNewIdList = [] //暂存遍历未找到的三级分类
                                        thirdLevelInfoNew.map((item)=>{
                                                let checkOff = true
                                                thirdLevelInfo.map((item1)=>{
                                                        if (item1.productCategoryId == item.productCategoryId){
                                                                checkOff = false
                                                                if (item.productList){
                                                                        item.productList.map((item2)=>{
                                                                                item1.productList.push(item2)
                                                                        })
                                                                }
                                                        }
                                                }) 
                                                if (checkOff){
                                                        thirdLevelInfoNewIdList.push(item.productCategoryId) 
                                                }       
                                        })
                                        if (thirdLevelInfoNewIdList.length > 0 && thirdLevelInfoNew.length > 0){
                                                thirdLevelInfoNewIdList.map((item)=>{
                                                        thirdLevelInfoNew.map((item1)=>{
                                                                if (item == item1.productCategoryId) {
                                                                        thirdLevelInfo.push(item1)    
                                                                }
                                                        })
                                                        
                                                })
                                        }
                                }
                        }else{
                                thirdLevelInfo = thirdLevelInfoNew
                        }
                        this.setData({
                                thirdLevelInfo: thirdLevelInfo
                        })
                        console.info("thirdLevelInfo--" + JSON.stringify(this.data.thirdLevelInfo))
                }else{
                        this.setData({
                                thirdLevelInfo: []
                        })   
                }

        },

        //监听页面的滚动事件
        onPageScroll: function(e) {
                console.log(e.scrollTop);
                this.data.scrollTop = e.scrollTop
                // if (e.scrollTop >= 0) {
                //         this.setData({
                //                 isUp: true
                //         })
                // } else {
                //         this.setData({
                //                 isUp: false
                //         })
                // }
        },

        //点击购物车事件
        addProductToCart(e) {
                //console.info("e--"+JSON.stringify(e))
                let productId = e.currentTarget.dataset.productid
                this.selectComponent('#bottomFrame').showFrame(productId, "addCart");
                //console.info("e--" + JSON.stringify(e))
                this.data.eInfo = e
        },

        //属性选择弹窗完成后数据回传函数
        selectedInfo(data) {
                //console.info("属性数据回收了--" + JSON.stringify(data))
                this.selectComponent('#addCart').touchOnGoods(this.data.eInfo);
        },

        //一级分类的事件
        firstLevelFun(id) {
                let _this = this
                let isShowSecond = _this.data.isShowSecond
                console.log("id--" + id);
                let firstLevelInfo = this.data.firstLevelInfo
                let secondLevelInfo = this.data.secondLevelInfo
                let showSecondLevel = []
                if (firstLevelInfo.length > 0) {
                        firstLevelInfo.map((item) => {
                                if (item.id == id) {
                                        if (item.isSelsected == false) {
                                                item.isSelsected = true
                                                console.log("开始发送请求");
                                                //发送请求 
                                        }
                                } else {
                                        item.isSelsected = false
                                }
                        })
                }
                if (secondLevelInfo.length > 0) {
                        secondLevelInfo.map((item) => {
                                if (item.parentId == id) {
                                        item.isSelsected = false
                                        showSecondLevel.push(item)
                                }
                        })
                        console.info("showSecondLevel--" + JSON.stringify(showSecondLevel))
                        if (showSecondLevel.length > 0) {
                                showSecondLevel[0].isSelsected = true
                                _this.getProductrequest(showSecondLevel[0].id, (data) => {
                                        _this.formateDateFromProductList(data)
                                })
                                isShowSecond =true
                        }else{
                                _this.getProductrequest(id, (data) => {
                                        _this.formateDateFromProductList(data)
                                })
                                isShowSecond = false
                        }

                }
                this.setData({
                        isShowSecond: isShowSecond,
                        pageNum: 1,
                        firstLevelInfo: firstLevelInfo,
                        showSecondLevel: showSecondLevel
                })
                wx.pageScrollTo({
                        scrollTop: 0,
                        duration: 300
                })
        },

        //一级分类的点击事件
        firstLevelTap(e) {
                this.firstLevelFun(e.target.dataset.id)
        },

        //二级分类点击事件
        secondLevelFun(id,callback){
                console.log("id" + JSON.stringify(id));
                let _this = this
                let showSecondLevel = this.data.showSecondLevel
                if (showSecondLevel.length > 0) {
                        showSecondLevel.map((item) => {
                                console.log("item" + JSON.stringify(item));
                                if (item.id == id) {
                                        if (item.isSelsected == false) {
                                                item.isSelsected = true
                                                console.log("开始发送请求");
                                                _this.getProductrequest(id, (data) => {
                                                        _this.formateDateFromProductList(data)
                                                        if (callback){
                                                                callback() 
                                                        }
                                                })
                                        }
                                } else {
                                        item.isSelsected = false
                                }
                        })
                }
                this.setData({
                        pageNum: 1,
                        showSecondLevel: showSecondLevel
                })
        },

        //二级分类点击事件
        secondLevelTap(e) {
                this.secondLevelFun(e.currentTarget.dataset.id)
        },

        //下拉刷新
        onPullDownRefresh() {
                wx.showNavigationBarLoading();
                let showSecondLevel = this.data.showSecondLevel
                // //console.info("下拉刷新的时间被触发showSecondLevel--"+JSON.stringify(showSecondLevel))
                let selectIndex = ""
                if (showSecondLevel.length > 0){
                        showSecondLevel.map((item,index)=>{
                                if (item.isSelsected){
                                        selectIndex = index
                                }
                        })
                        // //console.info("selectIndex--" + selectIndex)
                        if (selectIndex == 0) {
                                wx.showToast({
                                        title: '已经到顶了',
                                        icon: "none",
                                        duration: 1000,
                                })
                                wx.stopPullDownRefresh()
                        } else {
                                selectIndex--
                                let id = ""
                                showSecondLevel.map((item, index) => {
                                        if (index == selectIndex) {
                                                id = item.id
                                        }
                                })
                                if (id != ""){
                                        this.secondLevelFun(id,()=>{
                                                wx.stopPullDownRefresh()   
                                        })
                                }   
                        }
                }     
        },

        //上啦加载
        onReachBottom(e) {
                let _this = this
                //console.info("下拉加载被触发了")
                let showSecondLevel = this.data.showSecondLevel
                //console.info("下拉刷新的时间被触发showSecondLevel--"+JSON.stringify(showSecondLevel))
                let selectIndex = ""
                let id = ""
                let checkNext = this.data.checkNext
                if (showSecondLevel.length > 0) {
                        showSecondLevel.map((item, index) => {
                                if (item.isSelsected) {
                                        selectIndex = index
                                        id = item.id
                                }
                        })
                        // //console.info("selectIndex--" + selectIndex)
                        if (checkNext){
                                selectIndex++
                                showSecondLevel.map((item, index) => {
                                        if (selectIndex == index) {
                                                id = item.id
                                        }
                                }) 
                                this.secondLevelFun(id, () => {
                                        this.setData({
                                                checkNext : false        
                                        })
                                        wx.pageScrollTo({
                                                scrollTop: 0,
                                                duration: 300
                                        })
                                })
                        }else{
                                if (selectIndex == showSecondLevel.length - 1){
                                        wx.showToast({
                                                title: '没有更多了',
                                                icon: "none",
                                                duration: 2000
                                        })
                                }else{
                                        let pageNum = this.data.pageNum
                                        pageNum++
                                        this.setData({
                                                pageNum: pageNum
                                        })
                                        //console.info("下拉刷新的id--" + JSON.stringify(id))
                                        _this.getProductrequest(id, (data) => {
                                                //console.info("下拉刷新的data--" + JSON.stringify(data))
                                                if (data.length > 0) {
                                                        this.formateDateFromProductList(data, "push")
                                                } else {
                                                        this.setData({
                                                                pageNum: 1,
                                                                checkNext: true
                                                        })
                                                        wx.showToast({
                                                                title: '到底了，再上拉切换下个分类',
                                                                icon: "none",
                                                                duration: 2000
                                                        })
                                                }
                                        })
                                }
                                let scrollTop = this.data.scrollTop - 50
                                wx.pageScrollTo({
                                        scrollTop: scrollTop,
                                        duration: 300
                                })
                        }  
                } else{
                        let firstLevelInfo = this.data.firstLevelInfo
                        let firstLevelSelecetedId = ""
                        if (firstLevelInfo.length > 0) {
                                firstLevelInfo.map((item) => {
                                        if (item.isSelsected == true) {
                                                firstLevelSelecetedId = item.id
                                        } 
                                })
                                //console.info("firstLevelSelecetedId--" + firstLevelSelecetedId)
                                let pageNum = this.data.pageNum
                                pageNum++
                                this.setData({
                                        pageNum: pageNum
                                })
                                _this.getProductrequest(firstLevelSelecetedId, (data) => {
                                        //console.info("下拉刷新的data--" + JSON.stringify(data))
                                        if (data.length > 0) {
                                                this.formateDateFromProductList(data, "push")
                                        } else {
                                                wx.showToast({
                                                        title: '没有更多了',
                                                        icon: "none",
                                                        duration: 2000
                                                })
                                        }
                                        let scrollTop = this.data.scrollTop - 50
                                        wx.pageScrollTo({
                                                scrollTop: scrollTop,
                                                duration: 300
                                        })
                                })
                        }
                }
        },
})